#include <chrono>
#include <memory>
#include <string>

#include "rclcpp/rclcpp.hpp"
#include "rclcpp_components/register_node_macro.hpp"
#include "std_msgs/msg/string.hpp"

using namespace std::chrono_literals;

namespace multi_launch_demo
{

class ComponentPublisher : public rclcpp::Node
{
   public:
    ComponentPublisher(const rclcpp::NodeOptions &options) : Node("component_publisher", options)
    {
        // 声明参数
        this->declare_parameter("publish_frequency", 1.0);
        this->declare_parameter("message_prefix", "Component");

        // 获取参数
        double frequency = this->get_parameter("publish_frequency").as_double();
        std::string prefix = this->get_parameter("message_prefix").as_string();

        // 创建发布者
        publisher_ = this->create_publisher<std_msgs::msg::String>("component_topic", 10);

        // 创建定时器
        timer_ = this->create_wall_timer(
            std::chrono::milliseconds(static_cast<int>(1000.0 / frequency)), [this, prefix]() -> void {
                auto message = std_msgs::msg::String();
                message.data = prefix + " from component_publisher " + std::to_string(count_++);
                RCLCPP_INFO(this->get_logger(), "Component Publishing: '%s'", message.data.c_str());
                publisher_->publish(message);
            });

        RCLCPP_INFO(this->get_logger(), "Component Publisher started with frequency: %.1f Hz", frequency);
    }

   private:
    rclcpp::Publisher<std_msgs::msg::String>::SharedPtr publisher_;
    rclcpp::TimerBase::SharedPtr timer_;
    int count_ = 0;
};

}  // namespace multi_launch_demo

RCLCPP_COMPONENTS_REGISTER_NODE(multi_launch_demo::ComponentPublisher)
